var config = require('../../config.js');
let qd = {
  /*
  获取app信息
   */
  appInfo: function (option) {
    wx.request({
      url: config.api + 'app',
      data: {
        id: config.aid
      },
      success: function (response) {
        option.success(response);
      }
    })
  },
  /*
  用户登录
   */
  login: function (option) {
    //TODO 要对fail进行处理
    //先获取微信用户授权信息
    wx.getSetting({
      success: settingRes => {
        if (settingRes.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取微信用户信息
          wx.getUserInfo({
            success: UserInfoRes => {
              wx.login({
                success: loginRes => {
                  wx.request({
                    url: config.api + 'login',
                    data: {
                      aid: config.aid,
                      code: loginRes.code,
                      rawData: UserInfoRes.rawData
                      //TODO 最好对rawData进行缓存对比，当rawData变更时才提交rawData，因为微信用户不会经常修改资料
                    },
                    success: requestRes => {
                      if (requestRes.data.code === 0) {
                        let token = requestRes.data.data;
                        wx.setStorageSync('user_token', token);
                        option.success(requestRes);
                      } else {
                        wx.showModal({
                          title: requestRes.data.msg,
                          content: requestRes.data.data,
                          showCancel: false
                        });
                        option.fail(requestRes);
                      }
                    }
                  })
                }
              })
            }
          })
        }else{
          // 没有授权，关闭所有页面，跳转到auth页面
          wx.reLaunch({
            url: '../auth/index'
          })
        }
      }
    })
  },
  /*
获取用户信息
 */
  userToken: function (option) {
    let token = wx.getStorageSync('user_token');
    if (token) {
      option.success(token);
    } else {
      this.login({
        success: function (res) {
          option.success(res.data.data);
        }
      });
    }
  },
  request: function (option) {
    //console.log(option);
    let url = config.api + option.url;
    let data = option.data ? option.data : {};
    if (option.login) {
      this.userToken({
        success: res => {
          data.token = res
        }
      })
    }
    wx.request({
      url: url,
      data: data,
      success: function (res) {
        option.success(res);
      }
    })
  }
};
module.exports = qd;